import React from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Modal,
  Form,
  Tag,
  Space,
  message,
  Select,
  Popconfirm,
  Tabs,
  Switch,
} from 'antd';

// 机器组页面（模仿 admin-web 的 MachineGroup.vue）
export default function MachineGroup() {
  // 搜索条件
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ userName: '', name: '' });

  // 列表与分页
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [loading, setLoading] = React.useState(false);

  // 新增/编辑分组
  const [groupForm] = Form.useForm();
  const [dialogUserMachineGroup, setDialogUserMachineGroup] = React.useState(false);
  const [editing, setEditing] = React.useState(null);

  // 转移分组
  const [dialogMoveUserMachineGroup, setDialogMoveUserMachineGroup] = React.useState(false);
  const [teamId, setTeamId] = React.useState('');
  const [moveTargetId, setMoveTargetId] = React.useState('');

  // 批量配置设备
  const [dialogConfigMachine, setDialogConfigMachine] = React.useState(false);
  const [configSubmit, setConfigSubmit] = React.useState({ id: '', config: { info: {}, manager: {}, remote: {}, model: {}, vatRate: {}, shopping: {}, age: {}, elock: {}, advert: {} } });

  // 字典集（模拟）
  const [portSet, setPortSet] = React.useState([]);
  const [baudSet, setBaudSet] = React.useState([]);
  const [modeList, setModeList] = React.useState([]);
  const [yesNo, setYesNo] = React.useState([]);
  const [ageDevice, setAgeDevice] = React.useState([]);
  const [ageType, setAgeType] = React.useState([]);
  const [priorityMode, setPriorityMode] = React.useState([]);
  const [IdcardCountry, setIdcardCountry] = React.useState([]);
  const [feelLock, setFeelLock] = React.useState([]);

  // 设备组数据（模拟）
  const [groups, setGroups] = React.useState(() => ([
    { id: 1, nickName: '王五', name: '华东一区', desc: '江浙沪设备组', deviceCount: 58, online: 52, offline: 6, updatedAt: '2025-10-01 12:10' },
    { id: 2, nickName: '李四', name: '华南一区', desc: '广东广西设备组', deviceCount: 43, online: 39, offline: 4, updatedAt: '2025-10-01 11:22' },
    { id: 3, nickName: '张三', name: '西南一区', desc: '川渝设备组', deviceCount: 31, online: 27, offline: 4, updatedAt: '2025-10-01 10:15' },
    { id: 4, nickName: '赵六', name: '华北一区', desc: '京津冀设备组', deviceCount: 49, online: 44, offline: 5, updatedAt: '2025-09-30 17:40' },
  ]));

  // 模拟获取字典配置
  React.useEffect(() => {
    setLoading(true);
    const timer = setTimeout(() => {
      setPortSet(['串口A', '串口B']);
      setBaudSet(['9600', '19200', '115200']);
      setModeList(['普通', '高级', '自定义']);
      setYesNo([
        { label: '是', value: 1 },
        { label: '否', value: 0 },
      ]);
      setAgeDevice(['摄像头A', '摄像头B']);
      setAgeType(['身份证', '人脸', '二维码']);
      setPriorityMode(['先付款', '先取货']);
      setIdcardCountry(['CN', 'US', 'JP']);
      setFeelLock(['启用', '禁用']);
      setLoading(false);
    }, 400);
    return () => clearTimeout(timer);
  }, []);

  // 过滤与分页数据
  const filtered = React.useMemo(() => {
    let list = groups;
    if (search.userName) {
      list = list.filter(g => String(g.nickName).includes(search.userName));
    }
    if (search.name) {
      list = list.filter(g => String(g.name).includes(search.name));
    }
    return list;
  }, [groups, search]);

  const pagedData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  // 表格列（模仿 Vue：nickName、name、操作）
  const columns = [
    { title: '用户昵称', dataIndex: 'nickName', align: 'center' },
    { title: '分组名称', dataIndex: 'name', align: 'center' },
    {
      title: '设备数',
      dataIndex: 'deviceCount',
      width: 200,
      align: 'center',
      render: (_, r) => (
        <Space>
          <Tag color="success">在线 {r.online}</Tag>
          <Tag color="error">离线 {r.offline}</Tag>
          <Tag>{r.deviceCount} 台</Tag>
        </Space>
      ),
    },
    { title: '更新时间', dataIndex: 'updatedAt', width: 200, align: 'center' },
    {
      title: '操作',
      key: 'operate',
      fixed: 'right',
      align: 'center',
      width: 360,
      render: (_, row) => (
        <Space wrap>
          <Button size="small" onClick={() => editMachineGroup(row)}>编辑</Button>
          <Button size="small" type="warning" onClick={() => transferMachine(row)}>转移设备</Button>
          <Button size="small" type="primary" onClick={() => configUserMachine(row)}>批量配置</Button>
          <Popconfirm title={`确认删除分组“${row.name}”吗？`} onConfirm={() => delMachineGroup(row)}>
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 搜索事件
  const onSearchSubmit = async () => {
    const values = await searchForm.validateFields();
    setSearch(values);
    setPageIndex(1);
  };
  const onResetSearch = () => {
    searchForm.resetFields();
    setSearch({ userName: '', name: '' });
    setPageIndex(1);
  };

  // 分组新增/编辑
  const addUserMachineGroup = () => {
    setEditing(null);
    groupForm.resetFields();
    setDialogUserMachineGroup(true);
  };
  const editMachineGroup = (row) => {
    setEditing(row);
    groupForm.setFieldsValue({ name: row.name, desc: row.desc });
    setDialogUserMachineGroup(true);
  };
  const saveUserMachineGroup = async () => {
    const values = await groupForm.validateFields();
    if (editing) {
      setGroups(prev => prev.map(g => g.id === editing.id ? { ...g, ...values } : g));
      message.success('设备组已更新');
    } else {
      const maxId = Math.max(0, ...groups.map(g => g.id));
      setGroups(prev => [{ id: maxId + 1, nickName: '新用户', online: 0, offline: 0, deviceCount: 0, updatedAt: new Date().toLocaleString(), ...values }, ...prev]);
      message.success('设备组已新增');
    }
    setDialogUserMachineGroup(false);
  };

  // 分组转移
  const transferMachine = (row) => {
    setDialogMoveUserMachineGroup(true);
    setTeamId(String(row.id));
  };
  const confirmTransfer = () => {
    if (!moveTargetId) {
      message.warning('请选择目标分组');
      return;
    }
    if (moveTargetId === teamId) {
      message.warning('目标分组不能与当前分组相同');
      return;
    }
    setDialogMoveUserMachineGroup(false);
    message.success('设备已转移到目标分组（模拟）');
  };

  // 批量配置
  const configUserMachine = (row) => {
    setConfigSubmit(prev => ({ ...prev, id: row.id }));
    setDialogConfigMachine(true);
  };
  const configCancel = () => {
    setDialogConfigMachine(false);
    // 模拟刷新
    setPageIndex(1);
  };

  // 删除分组
  const delMachineGroup = (row) => {
    setGroups(prev => prev.filter(g => g.id !== row.id));
    message.success('删除成功');
  };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      {/* 搜索与新增 */}
      <Card variant="borderless">
        <Form form={searchForm} layout="inline" initialValues={search} style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <Form.Item name="userName" label="用户名称">
            <Input allowClear placeholder="请输入用户名称" style={{ width: 220 }} />
          </Form.Item>
          <Form.Item name="name" label="分组名称">
            <Input allowClear placeholder="请输入分组名称" style={{ width: 220 }} />
          </Form.Item>
          <Space>
            <Button type="primary" onClick={onSearchSubmit}>查询</Button>
            <Button onClick={onResetSearch}>重置</Button>
            <Button type="dashed" onClick={addUserMachineGroup}>新增分组</Button>
          </Space>
        </Form>
      </Card>

      {/* 列表 */}
      <Card title="机器组清单" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r) => r.id}
          loading={loading}
          dataSource={pagedData}
          columns={columns}
          pagination={{
            current: pageIndex,
            pageSize,
            total: filtered.length,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            onChange: (pi, ps) => {
              setPageIndex(pi);
              setPageSize(ps);
            },
          }}
        />
      </Card>

      {/* 新增/编辑分组 */}
      <Modal
        title={editing ? '编辑分组' : '新增分组'}
        open={dialogUserMachineGroup}
        onOk={saveUserMachineGroup}
        onCancel={() => setDialogUserMachineGroup(false)}
      >
        <Form form={groupForm} layout="vertical">
          <Form.Item name="name" label="分组名称" rules={[{ required: true, message: '请输入分组名称' }]}> 
            <Input placeholder="例如：华东一区" />
          </Form.Item>
          <Form.Item name="desc" label="备注/描述"> 
            <Input.TextArea rows={3} placeholder="可填写该组区域、用途等信息" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 转移分组 */}
      <Modal
        title="转移设备到其他分组"
        open={dialogMoveUserMachineGroup}
        onOk={confirmTransfer}
        onCancel={() => setDialogMoveUserMachineGroup(false)}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <div>当前分组ID：{teamId}</div>
          <Select
            value={moveTargetId}
            onChange={setMoveTargetId}
            style={{ width: '100%' }}
            placeholder="请选择目标分组"
            options={groups.map(g => ({ label: `${g.name}（ID: ${g.id}）`, value: String(g.id) }))}
          />
        </Space>
      </Modal>

      {/* 批量配置设备（简化版，模仿 Vue 的 ConfigUserMachine） */}
      <Modal
        title="设备批量配置"
        open={dialogConfigMachine}
        onOk={configCancel}
        onCancel={configCancel}
        width={800}
      >
        <Tabs
          items={[
            {
              key: 'info',
              label: '基础信息',
              children: (
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <span>是否开启优惠：</span>
                    <Select style={{ width: 160 }} options={yesNo.map(y => ({ label: y.label, value: y.value }))} />
                  </Space>
                  <Space>
                    <span>货道锁定：</span>
                    <Select style={{ width: 160 }} options={feelLock.map(f => ({ label: f, value: f }))} />
                  </Space>
                  <Space>
                    <span>币种符号：</span>
                    <Input style={{ width: 160 }} placeholder="￥" />
                  </Space>
                </Space>
              ),
            },
            {
              key: 'manager',
              label: '管理设置',
              children: (
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <span>开启管理员：</span>
                    <Switch />
                  </Space>
                  <Space>
                    <span>管理员密码：</span>
                    <Input.Password style={{ width: 200 }} />
                  </Space>
                </Space>
              ),
            },
            {
              key: 'model',
              label: '设备模式',
              children: (
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <span>设备模式：</span>
                    <Select style={{ width: 200 }} options={modeList.map(m => ({ label: m, value: m }))} />
                  </Space>
                  <Space>
                    <span>优先模式：</span>
                    <Select style={{ width: 200 }} options={priorityMode.map(m => ({ label: m, value: m }))} />
                  </Space>
                </Space>
              ),
            },
            {
              key: 'age',
              label: '年龄识别',
              children: (
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <span>识别设备：</span>
                    <Select style={{ width: 200 }} options={ageDevice.map(a => ({ label: a, value: a }))} />
                  </Space>
                  <Space>
                    <span>识别方式：</span>
                    <Select style={{ width: 200 }} options={ageType.map(a => ({ label: a, value: a }))} />
                  </Space>
                </Space>
              ),
            },
            {
              key: 'port',
              label: '通信/串口',
              children: (
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <span>串口：</span>
                    <Select style={{ width: 160 }} options={portSet.map(p => ({ label: p, value: p }))} />
                  </Space>
                  <Space>
                    <span>波特率：</span>
                    <Select style={{ width: 160 }} options={baudSet.map(b => ({ label: b, value: b }))} />
                  </Space>
                </Space>
              ),
            },
            {
              key: 'other',
              label: '其他',
              children: (
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <span>身份证国家：</span>
                    <Select style={{ width: 200 }} options={IdcardCountry.map(c => ({ label: c, value: c }))} />
                  </Space>
                </Space>
              ),
            },
          ]}
        />
        <div style={{ color: '#999', marginTop: 8 }}>注：以上为模拟配置项，实际表单请与后端接口字段对齐。</div>
      </Modal>
    </div>
  );
}